#! /usr/bin/env python3
import cgi
import urllib
import glob


def get_html(title, const):
    code_path = '<div></br>\n<center><h5>代码：' + title + '</h5></center>\n</br><pre><code>' + const + '</code><pre></div>'
    return code_path


def main(cpath):
    cgi_mod = cgi.FieldStorage()
    file_label = cgi_mod.getvalue('coder')
    file_path = urllib.parse.unquote(file_label)
    file_path = str(cpath) + "/" + file_path
    file_path = file_path.replace(" ", "?").replace(".", "?").replace("：", "?").replace("&amp;", "?")
    file_path = file_path.replace("，", "?").replace(",", "?").replace("&", "?")
    file_path = glob.glob(file_path)[0]
    file_name = file_path.split('/')[-1]
    last_const = ""
    with open(file_path, "r") as f:
        cont = f.read()
        cont = cont.replace('\r\n', '\n').replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')
        cont = cont.replace('<<', '&laquo;').replace('>>', '&raquo;').replace('`', '&acute;')
        last_const = get_html(file_name, cont)
    return last_const
